# coding: UTF-8
# Filename : chain_centerlist_api.py
# Company : imedia
# Author : zqz# -*-coding:utf-8 -*-
from api.common.common import *
from api.common import mysql,log,utils,httputils,const,xml_tpl, err_tpl
import chain_centerlist_data_model
import time
'''
http://api.imedia.com/app/part/list
'''
		
#details list
def chain_centerlist_list(request):
    #record log((frist action))
    httputils.footprint(request)
    #param
    user_id = httputils.post(request, 'user_id')#is customer id,more
    size = httputils.post(request, 'size')
    pagenum = httputils.post(request, 'pagenum')
    cus_id = httputils.post(request, 'cus_id')#is cus_id id,more
    if not utils.is_num(size): size = 5
    if not utils.is_num(pagenum): pagenum = 1
    if not utils.is_num(user_id): user_id = 1 

    if validate(request):
        return validate(request)

    #Verification
    output = chain_centerlist_data_model.imedia_start 
    output += get_body_str(user_id, size, pagenum, cus_id)
    output += chain_centerlist_data_model.imedia_end
    return response(output) 

#获取中间数据体
def get_body_str(user_id, size, pagenum, cus_id):
    '''
     按照userid查找对应的评论信息
     分别用target 对应不同的类别表，检索已经的名称
    '''
    #sql
    sql = '''
    select id, target, target_id, created_at,content  
    from chain_comment  
    where user_id=%s 
    and cus_id = %s
    and reply_id = 0  order by id desc
    limit %s, %s
    '''
    start_row = utils.get_star_row(size, pagenum)
    param = [int(user_id), int(cus_id), start_row, int(size)]
    rsts = mysql.doSearch(sql, param)
    body_str = ''
    i = 0
    #构造对应表字典
    a_table = {'0':'chain_product','1':'chain_part','2':'chain_activity'}
    #构造对应类别名称字典
    a_class = {'0':'商品','1':'分店','2':'活动'}
    for obj in rsts:
        i = i + 1
        body_template = chain_centerlist_data_model.imedia_body
        body_template = body_template.replace('{id}', str(obj[0]))
        #做 类别名称对应
        class_name = str(obj[1])
        body_template = body_template.replace('{class_id}', class_name)
        #查询实体，名称
        #参数一 为实体 id
        #参数二 类别id
        tagetname = target_name(str(obj[2]),str(obj[1]))
        body_template = body_template.replace('{target_id}', str(obj[2]))
        body_template = body_template.replace('{target_name}', tagetname)
        ISOTIMEFORMAT='%Y-%m-%d %X'
        start_time = time.strftime(ISOTIMEFORMAT,time.localtime(obj[3]))
        body_template = body_template.replace('{datetime}', start_time)
        body_template = body_template.replace('{content}', str(obj[4]))
        body_str += body_template
    return body_str

def target_name(target_id, classid):
    #构造对应表字典
    a_table = {'0':'chain_product','1':'chain_part','2':'chain_activity'}
    if not utils.is_num(classid) and classid < 0 and classid > 2:
        return 'unkown'

    sql = '''
    select name from '''+ a_table[str(classid)] +''' where id = %s
    '''
    param = [int(target_id)]
    rsts = mysql.get(sql, param)
    return rsts[0]


